package com.brotherly.mpgp.remoteinterface;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Base64;

public class User implements Serializable
{
    private static final long serialVersionUID = 3453767062123551141L;

    public String DevicePlatform;
    public String Device;
    public String UserAgent;
    public String IMSI;
    public String IMEI;
    public long LastAccess;
    public int VersionCode;
    public Map<String, String> Others = new HashMap<String, String>();

    public User()
    {}

    public Bitmap unbase64Portrait(String portrait)
    {
        byte[] bytes = Base64.decode(portrait, Base64.DEFAULT);
        Bitmap portrait_image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return portrait_image;
    }

    public String base64Portrait(Bitmap portraitimage)
    {
        String portrait = null;
        if (portraitimage != null)
        {
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            try
            {
                portraitimage.compress(CompressFormat.PNG, 100, output);
                output.close();

                portrait = Base64.encodeToString(output.toByteArray(), Base64.DEFAULT);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        return portrait;
    }

    public static User parseJSONString(JSONObject jsonobject) throws JSONException
    {
        User user = new User();
        user.LastAccess = System.currentTimeMillis();
        return user;
    }

    public static String toJSONString(User user) throws JSONException
    {
        JSONObject items = new JSONObject();
        items.put("last_access", user.LastAccess);
        JSONObject others = new JSONObject();
        for (Map.Entry<String, String> entry : user.Others.entrySet())
        {
            String key = entry.getKey();
            String value = entry.getValue();
            others.put(key, value);
        }
        items.put("others", others);

        return items.toString();
    }
}
